package com.decard.baselibrarydemo.utils;

import android.util.Log;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class IoControlUtils {
	private static final String TAG = "IoControlUtils";

	public static final String IC_CARDS_PATH = "/sys/dy_control/IC_cards_en";

	public static final String POGO_A_PORT_PATH = "/sys/dy_control/POGO_port_en";

	public static final String POGO_B_PORT_PATH = "/sys/dy_control/POGO_port2_en";

	public static final String SMART_READER_PATH = "/sys/dy_control/smartcard_en";

	//扫码上下电
	public static final String SCAN_ENGINE_RST_PATH = "/sys/dy_control/scan_engine_rst";

	//扫码器上下电
	public static final String SCAN_ENGINE_TRIG_PATH = "/sys/dy_control/scan_engine_trig";

	//扫码器使能脚上下电
	public static final String SCAN_ENGINE_PATH = "/sys/dy_control/scan_engine_en";

	//指纹模块
	public static final String ARATEK_FP_PATH = "/sys/aratek_control/aratek_fp_en";

	//USB上下电
	public static final String USB_PATH = "/sys/dy_usbdev_control/customer_prefer";

	private static IoControlUtils instance = new IoControlUtils();

	private IoControlUtils() {

	}

	public static IoControlUtils getInstance() {
		return instance;
	}

	public enum IOSTATUS {
		DISABLE, ENABLE
	}

	/**
	 * 设置IO口状态/ Set IO port status
	 * 
	 * @param path
	 * @param status
	 * @return
	 */
	public boolean setIoStatus(String path, IOSTATUS status) {
		return write(path, status.ordinal());
	}

	public int getIoStatus(String path) {
		return read(path);
	}

	private boolean write(String path, int value) {
		boolean success = false;
		BufferedWriter bufWriter = null;
		FileWriter fileWriter = null;
		try {
			fileWriter = new FileWriter(path);
			bufWriter = new BufferedWriter(fileWriter);
			bufWriter.write(String.valueOf(value));
			bufWriter.close();
			success = true;
			Log.d(TAG, "write success to value=" + value);
		} catch (IOException e) {
			e.printStackTrace();
			Log.e(TAG, "can't write the " + path);
		} finally {
			try {
				if (null != bufWriter) {
					bufWriter.close();
				}
				if (null != fileWriter) {
					fileWriter.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return success;
	}

	private int read(String path) {
		String value = "0";
		BufferedReader bufferedReader = null;
		FileReader fileReader = null;
		try {
			fileReader = new FileReader(path);
			bufferedReader = new BufferedReader(fileReader);
			value = bufferedReader.readLine();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (null != bufferedReader) {
					bufferedReader.close();
				}
				if (null != fileReader) {
					fileReader.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		Log.d(TAG, "read value=" + value);
		if (value.contains("customer perfer")){
			value=value.split(":")[1].substring(0,1);
			Log.d(TAG, "split value="+value);
		}
		return Integer.parseInt(value);

	}
}
